﻿using HomeCloudStorageSystem.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.WebUtilities;
using System.IO;
using HomeCloudStorageSystem.Helps;
using static System.Net.WebRequestMethods;
using System;
using HomeCloudStorageSystem.Dtos;
using Microsoft.AspNetCore.Authorization;
using System.Security.Claims;

namespace HomeCloudStorageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class FileInfosController : ControllerBase
    {
        private IFileInfosRepository _fileInfosRepository;
        private IUserRepository _userRepository;
        public FileInfosController(IFileInfosRepository fileInfosRepository, IUserRepository userRepository)
        {
            _fileInfosRepository = fileInfosRepository;
            _userRepository = userRepository;
        }
        /// <summary>
        /// 根据 ID 浏览文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        [AllowAnonymous]
        public IActionResult GetFileById([FromRoute] int id)
        {
            if (id == null)
            {
                return BadRequest("请求内容不能为空");
            }
            var fileInfoFromRep = _fileInfosRepository.GetFileInfosById(id);
            if (fileInfoFromRep == null)
            {
                return NotFound("没有数据");
            }
            var fileBytes = _fileInfosRepository.GetFileById(fileInfoFromRep.FilePath);
            if(fileBytes == null)
            {
                return NotFound("没有数据");
            }
            var types = ReadStreamHelp.GetMimeTypes();
            var extNameToLower = fileInfoFromRep.ExtName.ToLower();
            var contentType = types[extNameToLower];
            return File(fileBytes, contentType);
        }
        /// <summary>
        /// 根据目录 ID 查看 FileInfo
        /// </summary>
        /// <param name="directoryId">目录ID</param>
        /// <returns>FileInfo列表</returns>
        [HttpGet("fileInfos/{directoryId}")]
        public IActionResult GetFileInfosByDirectoryId(int directoryId)
        {
            if (directoryId <= 0 || string.IsNullOrEmpty(directoryId.ToString()))
            {
                directoryId = 0;
            }
            var fileInfosFromRep = _fileInfosRepository.GetFileInfosByDirectory(directoryId);
            return Ok(fileInfosFromRep);
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="files">需要上传的文件列表</param>
        /// <returns></returns>
        [HttpPost("upload")]
        public IActionResult Upload([FromForm] UploadFileDto UploadFileDto, [FromForm(Name = "files")] IEnumerable<IFormFile> files)
        {
            if (files == null || files.Count() == 0)
            {
                return BadRequest("不能上传空文件");
            }
            var userName = User.Claims.FirstOrDefault(n => n.Type == ClaimTypes.NameIdentifier)?.Value;
            var userInfo = _userRepository.GetUserByUserName(userName);
            _fileInfosRepository.AddFileInfos(files, userInfo.Id, UploadFileDto.Describe, UploadFileDto.FileDirectoryId, out Dictionary<string, string> message);
            return Ok(message);
        }
        /// <summary>
        /// 根据ID下载文件
        /// </summary>
        /// <param name="id">文件ID</param>
        /// <returns></returns>
        [HttpGet("doenload/{id}")]
        public IActionResult Download([FromRoute] int id)
        {
            var fileInfoFromRep = _fileInfosRepository.GetFileInfosById(id);
            if (fileInfoFromRep == null)
            {
                return NotFound("没有找到数据");
            }
            if (!System.IO.File.Exists(fileInfoFromRep.FilePath))
            {
                return NotFound("没有该文件");
            }
            var memory = new MemoryStream();
            using (var stream = new FileStream(fileInfoFromRep.FilePath, FileMode.Open))
            {
                stream.CopyTo(memory);
            }
            memory.Position = 0;
            int index = fileInfoFromRep.FileName.LastIndexOf('.');
            string fileExtensions = fileInfoFromRep.FileName.Substring(index);
            var type = ReadStreamHelp.GetContentType(fileExtensions);

            return File(memory, type, fileInfoFromRep.FileName);
        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="id">文件ID</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public IActionResult Delete([FromRoute] int id)
        {
            if (id <= 0 || string.IsNullOrEmpty(id.ToString()))
            {
                return BadRequest("错误的请求");
            }
            var fileIndoFromRep = _fileInfosRepository.GetFileInfosById(id);
            if (fileIndoFromRep == null)
            {
                return NotFound("没有找到数据");
            }
            if (!System.IO.File.Exists(fileIndoFromRep.FilePath))
            {
                return NotFound("没有找到数据");
            }
            _fileInfosRepository.RemoveFileInfo(fileIndoFromRep);
            return Ok("删除成功");
        }
    }
}
